from flask import Blueprint, request

from exts import db
from models import software_All

import random

bp = Blueprint("software", __name__, url_prefix="/software")

# 写入数据库`
# S_name
# S_picture
# S_tag
# S_details
@bp.route("/Event/write",methods=["POST"])
def Event_write():
    if request.method == "POST":
        # 判断是哪一种传参的方法
        if request.content_type.startswith('application/json'):
            S_name = request.json.get('S_name')
            S_picture = request.json.get('S_picture')
            S_tag = request.json.get('S_tag')
            S_details = request.json.get('S_details')
        elif request.content_type.startswith('multipart/form-data'):
            S_name = request.form.get('S_name')
            S_picture = request.form.get('S_picture')
            S_tag = request.form.get('S_tag')
            S_details = request.form.get('S_details')
        else:
            S_name = request.values.get("S_name")
            S_picture = request.values.get("S_picture")
            S_tag = request.values.get("S_tag")
            S_details = request.values.get('S_details')
        data=software_All(S_name=S_name,S_picture=S_picture,S_tag=S_tag,S_details=S_details)
        db.session.add(data)
        # 这个为添加数据到暂存区
        db.session.commit()
        return "正在写入"


# 读取软件列表（推荐软件？）         直接请求
@bp.route("/Event/read",methods=["GET"])
def Event_read():
    #创建一个范围的数据
    Random_=[]
    for item in range(1000):
        Random_.append(item)
    # 之后通过random这个方法来生成几个不重复的数据
    # 需要和上一次的不重复

    Random_data = random.sample(Random_,20)
    # 之后通过这几个随机数去读取数据并返回
    data=[]
    for item in Random_data:
        soft_list = software_All.query.filter_by(Sid=item)
        for anal_item in soft_list:
            analyze_list ={
                "id":anal_item.Sid,
                "name":anal_item.S_name,
                "picture":anal_item.S_picture,
                "tag":anal_item.S_tag
            }
            data.append(analyze_list)

    if len(data)==0:
        return {"code":"404",}
    else:
        return {"code": "200", "Recommended": "随机数","length":len(data), "data": data}




# 搜索应用
@bp.route("/search",methods=["GET"])
def search():

    # 搜索的字段
    search_name = request.values.get("search")
    if search_name is None:
        return {"code":404,"errno":"请携带参数"}
    elif search_name == "":
        return {"code":404,"errno":"参数请不要为空"}
    search_data = software_All.query.filter(software_All.S_name.contains(search_name)).all()
    search_len = len(search_data)
    data=[]
    if search_len == 0:
        return {"code":400,"error":"数据并未查询到，请换个关键词吧"}
    for item in search_data:
        search_temporarily={
        "id":item.Sid,
        "name":item.S_name,
        "picture":item.S_picture,
        "tag":item.S_tag
        }
        data.append(search_temporarily)
    return {"code":200,"length":search_len,"data":data}


# 返回全部软件，通过软件的网址来进行爬取软件的详情和是下载链接
@bp.route("/Event/all",methods=["GET"])
def Event_all():
    page_offset= 0
    page_limit= 20
    page_shangyic = 0
    limit_=20

    len_Event = len(software_All.query.filter_by().all())

    # 获取参数格式化
    page = request.values.get("page")
    if page:
        if page == "0":
            return {"code": 404}
        else:
            page = int(page)
            page_offset=(page-1)*page_limit
            page_limit=page * page_limit            #这个地方是算出有少个数据
    else:
        page=1



    if page_limit > len_Event:
        if page_limit - len_Event > 20 :
            return {"code": 404}
        elif page_limit - len_Event < 20:
            if page > 1:
                page_shangyic = (page - 1) * 20  # 这个地方是算出有少个数据
                limit_=len_Event-page_shangyic

                                #limit_这个为长度limit，长度要固定为20，当在不够20条数据的时候改一下
    data_all = software_All.query.order_by().offset(page_offset).limit(limit_).all()
    data_list=[]
    for item in data_all:
        data_list.append({
            "name": item.S_name,
            "id": item.Sid,
            "details": item.S_details,
            "picture":item.S_picture,
            "tag":item.S_tag

        })

    return {"code":"200","page_list":str(int(round(len_Event/20,0))),"data":data_list}




